import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_html/style.dart';
import 'package:tender_flutter/constant/app_constant.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/goods/api/api_goods.dart';
import 'package:tender_flutter/page/person/model/pay_params.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';
import 'package:tender_flutter/widgets/net_image.dart';

import 'model/goods_entity.dart';

class GoodsDetailPage extends StatefulWidget {
  final int goodsId;

  const GoodsDetailPage({Key key, this.goodsId}) : super(key: key);

  @override
  _GoodsDetailPageState createState() => _GoodsDetailPageState();
}

class _GoodsDetailPageState extends State<GoodsDetailPage> {
  LoadState _loadState = LoadState.State_Loading;

  Future _detailFuture;

  /// 详情
  GoodsList _detailEntity;

  /// 获取数据
  Future<ApiResponse<GoodsList>> _getDetail() async {
    return await ApiGoods.getGoods<GoodsList>(id: widget.goodsId);
  }

  FutureBuilder<ApiResponse<GoodsList>> _buildFutureBuilder() {
    return FutureBuilder(
        future: _detailFuture,
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<GoodsList>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              GoodsList entity = snapshot.data.result;
              _detailEntity = entity;
              if (snapshot.data.status == Status.SUCCESS) {
                _loadState = LoadState.State_Success;
              } else {
                _loadState = LoadState.State_Error;
              }
            } else if (snapshot.hasError) {
              _loadState = LoadState.State_Error;
            }
          }

          return LoadStateLayout(
            bgColor: ThemeColors.colorWhite,
            state: _loadState,
            successWidget: _initBody(),
          );
        });
  }

  @override
  void initState() {
    super.initState();

    _detailFuture = _getDetail();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeColors.colorWhite,
      appBar: _initAppBar(),
      body: _buildFutureBuilder(),
    );
  }

  /// 导航
  Widget _initAppBar() {
    return BaseAppBar(context, Text("详情", style: FonStyle.navTextStyle()),
        isShowLeading: true);
  }

  /// 内容
  Widget _initBody() {
    if (_detailEntity == null){return Container();}
    return Column(children: [
      Expanded(
          child: SingleChildScrollView(
              physics: BouncingScrollPhysics(),
              child: _initHtmlContent())),
      _initBottomLayout()
    ]);
  }

  Widget _initHtmlContent() {
    return Container(
      margin: EdgeInsets.all(ScreenAdapter.width(30)),
      child: Column(
        children: <Widget>[
          SizedBox(
            height: 10,
          ),
          AspectRatio(aspectRatio: 1.5,child: MyNetImage(
            url:
            _detailEntity.pic,
            radius: BorderRadius.circular(ScreenAdapter.width(5)),)
          ),
          SizedBox(
            height: 10,
          ),
          Row(
            children: <Widget>[
              // 天猫的标签实现
              Container(
                padding:
                EdgeInsets.only(left: 1, right: 1, top: 0, bottom: 0),
                margin: EdgeInsets.only(right: 5),
                decoration: BoxDecoration(
                    color: Colors.red,
                    border:
                    Border.all(color: Color(0xFFFF0000), width: 0.5),
                    borderRadius: BorderRadius.all(Radius.circular(5))),
                child: Text(
                  '特惠',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 10,
                  ),
                ),
              ),
              // 商品标题
              Expanded(child: Text(
                _detailEntity.title ?? "",
                style: TextStyle(
                  color: Colors.black,
                ),
                maxLines: 2,
                softWrap: true,
              ))
            ],
          ),
          SizedBox(
            height: 10,
          ),
          // 两个横向标签
          Row(
            children: <Widget>[
              Container(
                padding:
                EdgeInsets.only(left: 3, right: 3, top: 1, bottom: 1),
                decoration: BoxDecoration(
                    border:
                    Border.all(color: Color(0xFFFF0000), width: 0.5),
                    borderRadius: BorderRadius.all(Radius.circular(5))),
                child: Text(
                  '优选放心购',
                  style: TextStyle(
                    color: Colors.red,
                    fontSize: 10,
                  ),
                ),
              ),
              SizedBox(
                width: 10,
              ),
              Container(
                padding:
                EdgeInsets.only(left: 3, right: 3, top: 1, bottom: 1),
                decoration: BoxDecoration(
                    border: Border.all(color: Colors.deepOrangeAccent, width: 0.5),
                    borderRadius: BorderRadius.all(Radius.circular(5))),
                child: Text(
                  '包邮',
                  style: TextStyle(
                    color: Colors.deepOrangeAccent,
                    fontSize: 10,
                  ),
                ),
              )
            ],
          ),
          SizedBox(
            height: 10,
          ),
          // 价格信息
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: <Widget>[
              Text(
                '火爆价',
                style: TextStyle(color: Colors.grey, fontSize: 12, fontWeight: FontWeight.w500),
              ),
              Text(
                '￥',
                style: TextStyle(color: Colors.red, fontSize: 12),
              ),
              Text(
                "${_detailEntity.priceN}",
                style: TextStyle(color: Colors.red, fontSize: 20,fontWeight: FontWeight.bold),
              ),
              SizedBox(
                width: 10,
              ),
              Text(
                "￥${_detailEntity.priceO}",
                style: TextStyle(color: Colors.grey, fontSize: 12,decoration: TextDecoration.lineThrough),
              ),
            ],
          ),
          SizedBox(
            height: 2,
          ),
          Html(
            shrinkWrap: true,
            data: _getContentHtml(),
            style: {
              "html": Style(
                  backgroundColor: Colors.white,
                  fontSize: FontSize(ScreenAdapter.sp(30))
//              color: Colors.white,
                  ),
//            "h1": Style(
//              textAlign: TextAlign.center,
//            ),
              "a": Style(textDecoration: TextDecoration.none),
              "table": Style(
                backgroundColor: Color.fromARGB(0x50, 0xee, 0xee, 0xee),
              ),
              "tr": Style(
                border: Border(bottom: BorderSide(color: Colors.grey)),
              ),
              "var": Style(fontFamily: 'serif'),
            },
            onImageError: (dynamic exception, StackTrace stackTrace) {},
            onLinkTap: (url) {},
            onImageTap: (src) {
              // print("图片" + src);
              LRouter.navigatorCtx(context).push(Routes.imageBrowsePage,
                  arguments:
                      ImageBrowsePageArguments(images: [src], currentIndex: 0));
            },
          )
        ],
      ),
    );
  }

  Widget _initBottomLayout() {
    return Container(
      decoration: BoxDecoration(
        color: ThemeColors.colorWhite,
        border: Border(
          top: BorderSide(
            width: 0.5, //宽度
            color: ThemeColors.colorType19, //边框颜色
          ),
        ),
      ),
      height: ScreenAdapter.height(100),
      child: Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: InkWell(
                onTap: () {
                  LRouter.navigatorCtx(context)
                      .push(Routes.customerServicePage);
                },
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Icon(Icons.person_add_alt),
                      SizedBox(width: ScreenAdapter.width(10)),
                      Text("联系客服")
                    ])),
          ),
          Container(
            width: 1,
            height: 15,
            color: ThemeColors.colorType36,
          ),
          Expanded(
            flex: 1,
            child: InkWell(
                onTap: () {
                  PayParams params = PayParams();
                  params.goodsDes = "购买${_detailEntity.title}";
                  params.comboId = _detailEntity.id;
                  params.goodsPrice = _detailEntity.priceN.toDouble();
                  params.orderType = AppConstant.PAY_ORDER_SHOP;
                  LRouter.navigatorCtx(context).push(Routes.paymentPage,
                      arguments: PaymentPageArguments(payParams: params));
                },
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Icon(
                        Icons.shopping_cart_outlined,
                      ),
                      SizedBox(width: ScreenAdapter.width(10)),
                      Text("立即购买")
                    ])),
          )
        ],
      ),
    );
  }

  String _getContentHtml() {
    String c = """
    <div>${_detailEntity.detail ?? ""}</div>
     """;
    return c;
  }
}
